package com.ruicar.afs.cloud.batch.dayend.process;

import com.ruicar.afs.cloud.batch.dayend.handle.run.SystemJdbcConfig;
import com.ruicar.afs.cloud.batch.frame.AbsBatchRunner;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import com.ruicar.afs.cloud.common.modules.contract.enums.CollectionStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.DataSourceEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ExpenseStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ValidOrInvalidEnum;

import java.sql.*;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
public class DataInvalidBathRunner extends AbsBatchRunner {

    private SystemJdbcConfig systemJdbcConfig= SpringContextHolder.getBean(SystemJdbcConfig.class);

    @Override
    public void process(String param) {
        logger.info("读取==={}", loadBreakPoint());
        Connection contractManage = this.getConnection(systemJdbcConfig.getManage());
        Connection contractBasic = this.getConnection(systemJdbcConfig.getBasic());
        try{
            logger.info("-------------------------开始执行数据失效批次任务-------------------------");
            //执行数据失效跑批
            dataInvalid(contractManage,contractBasic);
        }catch (Exception e){
            logger.error("",e);
            throw new AfsBaseException(e.getMessage());
        }finally {
            clean(contractManage);
            clean(contractBasic);
        }
    }

    private void dataInvalid(Connection contractManage,Connection contractBasic){
        Date batchDate = new Date(batchDateInfo.getBatchDate().getTime());
        //查询需要失效的合同
        StringBuffer sqlQuery = new StringBuffer();
        sqlQuery.append(" select DISTINCT contract_no from manage_prepayment_apply ");
        sqlQuery.append(" where repay_date <= ? and data_source = ? and status = ? and del_flag='0' and (collection_status != ? or collection_status is null or collection_status='') ");
        PreparedStatement psQuery = null;
        ResultSet rsQuery = null;

        //更新罚息明细表
        StringBuffer sqlInterestDetail = new StringBuffer();
        sqlInterestDetail.append(" update basic_penalty_interest set ");
        sqlInterestDetail.append(" exempted_amt=exempted_amt-exempt_bill_mitigate, ");
        sqlInterestDetail.append(" real_exemption_amt=real_exemption_amt-exempt_bill_mitigate, ");
        sqlInterestDetail.append(" exempt_bill_mitigate=0,status = ? ");
        sqlInterestDetail.append(" where exempt_bill_mitigate>0 and contract_no = ? ");
        PreparedStatement psInterestDetail = null;

        //更新費用明细表
        StringBuffer sqlCostDetail = new StringBuffer();
        sqlCostDetail.append(" update basic_expense_record_detail set ");
        sqlCostDetail.append(" exempted_amt=exempted_amt-exempt_bill_mitigate, ");
        sqlCostDetail.append(" exemption_amt=exemption_amt-exempt_bill_mitigate, ");
        sqlCostDetail.append(" remaining_amt=remaining_amt+exempt_bill_mitigate, ");
        sqlCostDetail.append(" exempt_bill_mitigate=0, status = ? ");
        sqlCostDetail.append(" where exempt_bill_mitigate>0 and contract_no = ? ");
        PreparedStatement psCostDetail = null;

        //更新費用表
        StringBuffer sqlCost = new StringBuffer();
        sqlCost.append(" update basic_expense_record set   ");
        sqlCost.append(" exempted_amt=exempted_amt-exempt_bill_mitigate, ");
        sqlCost.append(" exemption_amt=exemption_amt-exempt_bill_mitigate, ");
        sqlCost.append(" remaining_amt=remaining_amt+exempt_bill_mitigate, ");
        sqlCost.append(" exempt_bill_mitigate=0,status = ? ");
        sqlCost.append(" where exempt_bill_mitigate>0 and contract_no = ? ");
        PreparedStatement psCost = null;

        //更新提前结清试算表
        StringBuffer sqlQuotation = new StringBuffer();
        sqlQuotation.append(" update manage_prepayment_quotation set status = ? ");
        sqlQuotation.append(" where contract_no in ( select contract_no from manage_prepayment_apply ");
        sqlQuotation.append(" where repay_date <= ? and (collection_status != ? or collection_status is null or collection_status='')) ");
        PreparedStatement psQuotation = null;

        //更新提前结清申请表
        StringBuffer sqlApply = new StringBuffer();
        sqlApply.append(" update manage_prepayment_apply set status = ? ");
        sqlApply.append(" where repay_date <= ? and (collection_status != ? or collection_status is null or collection_status = '') ");
        PreparedStatement psApply = null;

        try {
            psQuery = contractManage.prepareStatement(sqlQuery.toString());
            psQuery.setDate(1, batchDate);
            psQuery.setString(2, AfsEnumUtil.key(DataSourceEnum.icos));
            psQuery.setString(3, AfsEnumUtil.key(ValidOrInvalidEnum.valid));
            psQuery.setString(4, AfsEnumUtil.key(CollectionStatusEnum.SUCCESS_COLLECTION));
            rsQuery = psQuery.executeQuery();
            int count=0;
            psInterestDetail = contractBasic.prepareStatement(sqlInterestDetail.toString());
            psCostDetail = contractBasic.prepareStatement(sqlCostDetail.toString());
            psCost = contractBasic.prepareStatement(sqlCost.toString());
            if(rsQuery!= null){
                while (rsQuery.next()) {
                    String contractNo = rsQuery.getString("contract_no");
                    //罚息信息表
                    psInterestDetail.setString(1, AfsEnumUtil.key(ExpenseStatusEnum.unsettle));
                    psInterestDetail.setString(2, contractNo);
                    psInterestDetail.addBatch();

                    //费用明细表
                    psCostDetail.setString(1, AfsEnumUtil.key(ExpenseStatusEnum.unsettle));
                    psCostDetail.setString(2, contractNo);
                    psCostDetail.addBatch();

                    //费用汇总表
                    psCost.setString(1, AfsEnumUtil.key(ExpenseStatusEnum.unsettle));
                    psCost.setString(2, contractNo);
                    psCost.addBatch();
                    count++;
                }
                logger.info("-------------------------共查询到【{}】条提前结清失效数据-------------------------",count);

                logger.info("-------------------------开始执行更新罚息明细表-------------------------");
                psInterestDetail.executeBatch();
                logger.info("-------------------------开始执行更新費用明细表-------------------------");
                psCostDetail.executeBatch();
                logger.info("-------------------------开始执行更新費用表-------------------------");
                psCost.executeBatch();
                contractBasic.commit();

                //提前结清试算表
                psQuotation = contractManage.prepareStatement(sqlQuotation.toString());
                psQuotation.setString(1, AfsEnumUtil.key(ValidOrInvalidEnum.invalid));
                psQuotation.setDate(2, batchDate);
                psQuotation.setString(3, AfsEnumUtil.key(CollectionStatusEnum.SUCCESS_COLLECTION));
                logger.info("-------------------------开始执行更新提前结清试算表-------------------------");
                psQuotation.executeUpdate();

                //提前结清申请表
                psApply = contractManage.prepareStatement(sqlApply.toString());
                psApply.setString(1, AfsEnumUtil.key(ValidOrInvalidEnum.invalid));
                psApply.setDate(2, batchDate);
                psApply.setString(3, AfsEnumUtil.key(CollectionStatusEnum.SUCCESS_COLLECTION));
                logger.info("-------------------------开始执行更新提前结清申请表-------------------------");
                psApply.executeUpdate();
                contractManage.commit();
            }
        } catch (SQLException e) {
            logger.error(e.getMessage());
            throw new AfsBaseException(e.getMessage());
        } finally {
            clean(psQuery);
            clean(rsQuery);
            clean(psInterestDetail);
            clean(psCostDetail);
            clean(psCost);
            clean(psQuotation);
            clean(psApply);
        }








    }


}
